package com.feige.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feige.dao.UserAnswerMapper;
import com.feige.pojo.Exercise;
import com.feige.pojo.Fraction;
import com.feige.pojo.UserAnswer;
import com.feige.result.AjaxResult;
import com.feige.service.ExerciseService;
import com.feige.service.FractionService;
import com.feige.service.UserAnswerService;
import com.feige.utils.jwt.JwtUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author feige
 * @since 2021-04-01
 */
@Service
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer> implements UserAnswerService {

    @Resource
    private ExerciseService exerciseService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private FractionService fractionService;



    @Override
    public AjaxResult correctAndSave(String token, String exerciseTitleId, List<UserAnswer> userAnswers) {
        AtomicInteger fraction = new AtomicInteger(0);
        String userId = jwtUtils.getUserIdByToken(token);
        QueryWrapper<Exercise> wrapper = new QueryWrapper<>();
        wrapper.
                select("id","type_value","answer","point")
                .eq("exercise_title_id",exerciseTitleId)
                .orderByAsc("type_value");
        // 批改
        List<Exercise> list = exerciseService.list(wrapper);
        list.forEach(e -> userAnswers.forEach(u -> {
            if (e.getId().equals(u.getExerciseId())){
                if (!e.getTypeValue().equals(5)){
                    if (e.getAnswer().equals(u.getAnswer())){
                        fraction.addAndGet(e.getPoint());
                    }
                }
            }
        }));
        // 把分数存入数据库
        Fraction f = new Fraction()
                .setUserId(userId)
                .setExerciseTitleId(exerciseTitleId)
                .setFraction(fraction.get());

        boolean save = fractionService.save(f);
        // 构造用户答案
        List<UserAnswer> collect = userAnswers.stream().peek(u -> {
            u.setUserId(userId);
        }).collect(Collectors.toList());
        // 用户答案持久化
        int saveBatch = this.baseMapper.insertBatch(collect);
        //返回分数
        if (saveBatch > 0 && save){
            return AjaxResult.success(fraction.get());
        }else {
            return AjaxResult.error();
        }
    }
}
